package com.baizhi.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * sentinel自定义规则
 */
@Configuration
public class SentinelRuleConfig {

    //https://github.com/alibaba/Sentinel/blob/master/sentinel-demo/sentinel-demo-basic/src/main/java/com/alibaba/csp/sentinel/demo/degrade/SlowRatioCircuitBreakerDemo.java
    @PostConstruct
    public void initRule(){

        //限流规则
        List<FlowRule> flowRules=new ArrayList<>();
        flowRules.add(productsFlowRule());

        FlowRuleManager.loadRules(flowRules);


        //服务降级或熔断规则
        List<DegradeRule> rules = new ArrayList<>();
         rules.add(degrade3Error());

        //放到熔断规则中云
        DegradeRuleManager.loadRules(rules);

    }

    /**
     * 1、每1秒钟如果3次访问，有3次出错，熔断60秒
     * @return
     */
    private DegradeRule degrade3Error(){
      DegradeRule  rule=new DegradeRule();
      rule.setResource("/productList2");
      rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
      rule.setCount(3);
      //熔断时长（单位s）
      rule.setTimeWindow(60);
      //最小请求数
      rule.setMinRequestAmount(3);
      //统计时长(单位毫秒)
        rule.setStatIntervalMs(1000);
      return rule;
    }


    ///products请求限流
    private FlowRule  productsFlowRule(){
        FlowRule flowRule=new FlowRule();
        flowRule.setResource("/products");
        flowRule.setCount(10);
        //qps
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        return flowRule;
    }


}
